import hashlib

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse

from .models import User
from .forms import SignupForm


def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)

        # 验证表单
        if form.is_valid():
            name = form.cleaned_data['name']
            password = form.cleaned_data['password']
            password_sha1 = sha1sum(password)
            cellphone = form.cleaned_data['cellphone']
            if User.objects.filter(name=name).count() == 0:
                user = User(name=name, password=password_sha1, cellphone=cellphone)
                user.save()
                return HttpResponseRedirect(reverse('app1:index'))
    else:
        form = SignupForm()
    return render(request, 'app1/signup.html', {'form': form})


def index(request):
    # 显示所有的注册用户的名字
    users = User.objects.all()
    return render(request, 'app1/index.html', {'users': users})


def sha1sum(data):
    return hashlib.sha1(data.encode()).hexdigest()
